package dongze.com.ckdj.util;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AlertDialog;
import android.util.Log;

import com.google.gson.Gson;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;

import dongze.com.ckdj.activity.UserPreferenceActivity;
import dongze.com.ckdj.dagger.DataStore;
import dongze.com.ckdj.dagger.component.AppComponent;
import dongze.com.ckdj.dagger.component.DaggerSectionComponent;
import dongze.com.ckdj.dagger.component.DaggerUserComponent;
import dongze.com.ckdj.dagger.component.DaggerVehicleComponent;
import dongze.com.ckdj.dagger.component.SectionComponent;
import dongze.com.ckdj.dagger.component.UserComponent;
import dongze.com.ckdj.dagger.component.VehicleComponent;
import dongze.com.ckdj.dagger.module.SectionModule;
import dongze.com.ckdj.dagger.module.UserModule;
import dongze.com.ckdj.dagger.module.VehicleModule;
import dongze.com.ckdj.data.entity.response.BrandResponse;
import dongze.com.ckdj.data.entity.response.InspectionSectionResponse;
import dongze.com.ckdj.data.entity.response.User;
import dongze.com.ckdj.data.entity.response.VehicleInformationDetail;


/**
 * Created by fanqwz on 2017/8/10.
 */

public class Util {
    private static final String TAG = Util.class.getSimpleName();
    private static final String TMP = "tmp";
    private static final String IMAGE_PATH = "/DZDJ/image";
    public static final String PREF_UPLOAD_BACKGROUND = "pref_upload_background";
    public static final String PREF_UPLOAD_BACKGROUND_AUTO_START = "pref_upload_background";
    public static final String PREF_AUTO_START = "pref_auto_start";
    public static final String PREF_SELECTED_BRAND = "pref_brand_name";
    public static final String PREF_4G_DOWNLOAD = "pref_4g_download_support";
    public static final String PREF_SELECTED_INSPECTION_SECTION = "pref_inspection_section";
    public static final String ENABLE = "enable";
    public static final String DISABLE = "disable";

    public static String getCurrentTime(Context context) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm", context.getResources().getConfiguration().locale).format(new GregorianCalendar().getTime());
    }

    public static File getImageTempDir() {
        File f = new File(Environment.getExternalStorageDirectory() + IMAGE_PATH, "cache");

        if (f.exists() && f.isFile()) {
            f.delete();
        }

        if (!f.exists())
            f.mkdirs();

        return f;
    }

    public static File getTempImageFile() {
        return getImageFile(TMP);
    }

    public static File getImageFile(String prifix) {
        File dir = new File(Environment.getExternalStorageDirectory() + IMAGE_PATH + File.separator + prifix);
        if (dir.exists() && !dir.isDirectory())
            dir.delete();

        if (!dir.exists())
            dir.mkdirs();

        return new File(dir,
                new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date())
                        + ".jpg");
    }

    public static void deleteFile(String path) {
        File f = new File(path);

        try {
            if (f.exists()) {
                f.delete();
            }
        } catch (Exception e) {
            MyLog.e(TAG, "deleteImage: " + path, e);
        }

    }

    public static String getPreference(Context context, String key, String def) {
        return PreferenceManager.getDefaultSharedPreferences(context).getString(key, def);
    }

    public static void setPreference(Context context, String key, String def) {
        PreferenceManager.getDefaultSharedPreferences(context).edit()
                .putString(key, def)
                .commit();
    }

    public static void ViewImage(Context context, File path) {
        try {
            Uri uri = Uri.fromFile(path);
            if (Build.VERSION.SDK_INT >= 24) {
                uri = FileProvider.getUriForFile(context, "dongze.com.ckdj.fileprovider", path);
            }
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            intent.setDataAndType(uri, "image/*");
            if (Build.VERSION.SDK_INT >= 24) {
                intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            }
            context.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static SectionComponent buildSectionComponent(UserComponent userComponent, DataStore dataStore) throws Exception {
        try {
            return DaggerSectionComponent.builder()
                    .userComponent(userComponent)
                    .sectionModule(new SectionModule(dataStore.get(BrandResponse.class), dataStore.get(InspectionSectionResponse.class)))
                    .build();
        } catch (Exception e) {
            throw new Exception("请先选择点检环节");
        }
    }

    public static UserComponent buildUserComponent(AppComponent appComponent, DataStore dataStore) throws Exception {
        try {
            return DaggerUserComponent.builder()
                    .appComponent(appComponent)
                    .userModule(new UserModule(dataStore.get(User.class)))
                    .build();
        } catch (Exception e) {
            throw new Exception("请先登陆");
        }
    }

    public static VehicleComponent buildVehicleComponent(SectionComponent sectionComponent, DataStore dataStore) throws Exception {
        try {
            return DaggerVehicleComponent.builder()
                    .sectionComponent(sectionComponent)
                    .vehicleModule(new VehicleModule(dataStore.get(VehicleInformationDetail.class)))
                    .build();
        } catch (Exception e) {
            throw new Exception("no vehicle information detail");
        }
    }

    public static void fillStringArrayNullValue(String[] v) {
        if (v == null)
            return;

        for (int i = 0; i < v.length; i++) {
            if (v[i] == null)
                v[i] = "";
        }
    }

    public static boolean checkCapturePermission(Context context) {
        if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            new AlertDialog.Builder(context)
                    .setMessage("没有拍照权限")
                    .create()
                    .show();
            return false;
        }
        return true;

    }
}
